#
# Copyright (c) 2023 supercell
#
# SPDX-License-Identifier: BSD-3-Clause
#
require "./inline_syntax"

module Luce
  # Matches autolinks like `<http://foo.com>`.
  class AutolinkSyntax < InlineSyntax
    def initialize
      super(%q{<(([a-zA-Z][a-zA-Z\-\+\.]+):(?://)?[^\s>]*)>})
    end

    def on_match(parser : InlineParser, match : Regex::MatchData) : Bool
      url = match[1]
      text = parser.encode_html? ? HTML.escape(url) : url
      anchor = Element.text("a", text)

      destination = Luce.normalize_link_destination(url)
      anchor.attributes["href"] =
        parser.encode_html? ? Luce.escape_html(destination) : destination
      parser.add_node(anchor)

      true
    end
  end
end
